import { Modal, message, Form, Upload, Input } from 'antd';
import type { RcFile, UploadProps, UploadChangeParam } from 'antd/es/upload';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { FC, useState, forwardRef, useImperativeHandle } from 'react';
import * as api from '@/api/product';

// 限制上传图片的格式
const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('图片格式必须为JPG/PNG!');
  }
  // 限制上传图片的大小
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }
  return isJpgOrPng && isLt2M;
};

type Iprops = {
  title: string;
  isModalOpen: boolean;
  category_id: string;
  getCategory: () => void;
  setIsModalOpen: (aa: boolean) => void;
};

let ModalBase = forwardRef<any, Iprops>((props, ref) => {
  // 使用hook获取form实例
  let [loginForm] = Form.useForm();
  // 解构从父组件传递来的值
  let { title, category_id, isModalOpen, getCategory, setIsModalOpen } = props;
  // 上传图片的地址
  const [imageUrl, setImageUrl] = useState<string>('');
  const [loading, setLoading] = useState(false);

  // 将子组件的方法或属性暴露给父组件
  useImperativeHandle(ref, () => {
    return {
      aa: setImageUrl,
      bb: loginForm.setFieldValue,
    };
  });

  // 当上传图片的地址改变时触发的回调
  let handleChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // console.log(info)
      // Get this url from response in real world.
      setLoading(false);
      setImageUrl(info.file.response.imgUrl);

      message.open({
        type: 'success',
        content: '上传成功',
      });
    }

    if (info.file.status === 'error') {
      setLoading(false);
      message.open({
        type: 'error',
        content: '上传失败',
      });
    }
  };

  // 模态框确定按钮
  const handleOk = async () => {
    // 让表单进行校验
    loginForm.submit();
  };

  // 模态框取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
    // 清空表单
    loginForm.resetFields();
    // 清空图片
    setImageUrl('');
  };

  // 表单校验通过
  const onFinish = async (values: any) => {
    let res = null;
    // console.log(values)

    if (title === '添加类目') {
      // 添加类目
      let obj = {
        categoryName: values.categoryName,
        categoryImgurl: imageUrl,
      };
      res = await api.addCategory(obj);
    } else {
      // 修改类目
      // console.log(name,imageUrl);
      let obj = {
        categoryName: values.categoryName,
        categoryImgurl: imageUrl,
        category_id: category_id,
      };
      console.log(imageUrl);
      res = await api.updateCategory(obj);
      // console.log(res)
    }
    if (res.data.state) {
      // 清空表单
      loginForm.resetFields();
      setImageUrl('');
      // 关闭模态框
      setIsModalOpen(false);
      // 更新列表
      getCategory();

      // 添加成功提示
      message.open({
        type: 'success',
        content: `${title}成功`,
        icon: <CheckCircleOutlined />,
      });
    } else {
      // 添加成功提示
      message.open({
        type: 'error',
        content: `${title}失败`,
        icon: <CheckCircleOutlined />,
      });
    }
  };

  // 表单校验失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <div>
      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={loginForm}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 8 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="类目图片">
            <Upload
              // {...imageData}
              action="/api/upload/uploadImg"
              name="img"
              method="post"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item
            label="类目名称"
            name="categoryName"
            rules={[{ required: true, message: '请输入类目名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
});

export default ModalBase;
